package org.bing.engine.console.service;

import java.util.List;

import org.bing.engine.core.domain.Application;
import org.bing.engine.core.domain.ApplicationOfDomain;
import org.bing.engine.core.domain.Domain;

@SuppressWarnings("unchecked")
public class ApplicationOfDomainManager extends AbstractHibernateManager {

    public List<ApplicationOfDomain> findByDomain(Domain domain) {
        if (domain == null) {
            return template.find("select t from ApplicationOfDomain t order by t.domain.name");
        } else {
            return template.find("select t from ApplicationOfDomain t where t.domain=?", domain);
        }
    }

    public ApplicationOfDomain findByDomainAndApplication(Domain domain, Application app) {
        String hql = "select t from ApplicationOfDomain t where t.domain=? and t.application=?";
        return (ApplicationOfDomain) super.findUniqueObject(hql, new Object[] { domain, app });
    }

    public List<Application> findApplicationByDomain(Domain domain) {
        if (domain == null) {
            return template.find("select distinct t.application from ApplicationOfDomain t order by t.application.name");
        } else {
            return template.find("select t.application from ApplicationOfDomain t where t.domain=?", domain);
        }
    }

    public void save(ApplicationOfDomain appOfDomain) {
        template.save(appOfDomain);
    }

    public void delete(ApplicationOfDomain appOfDomain) {
        if (appOfDomain.getId() > 0) {
            template.delete(appOfDomain);
        } else {
            String hql = "select t from ApplicationOfDomain t where t.application=? and t.domain=?";
            Object[] args = new Object[] { appOfDomain.getApplication(), appOfDomain.getDomain() };
            ApplicationOfDomain appOfDomain2 = (ApplicationOfDomain) super.findUniqueObject(hql, args);
            if (appOfDomain2 != null) {
                template.delete(appOfDomain2);
            } else {
                logger.warn("Can't find for " + appOfDomain + ", not delete.");
            }
        }
    }
}
